﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WMS.Common.WMS.Common;
using WMS.Model;
using WMS.Repository.IRepository;
using WMS.Service.IService;
using WMS.Service.Minio;

namespace wmsWebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IUserService _userService;
        private readonly ILogger<UserController> _logger;
        private readonly IMinioService _minioService;

        public UserController(IUserService userService, ILogger<UserController> logger, IMinioService minioService)
        {
            _userService = userService;
            _logger = logger;
            _minioService = minioService;
        }

        /// <summary>
        /// 分页查询用户列表
        /// </summary>
        [HttpGet("GetUserPagedListAsync")]
        public async Task<ResultApi> GetUserPagedListAsync(string account = null, string realname = null, string email = null, string phone = null, byte? status = null, int pageIndex = 1, int pageSize = 20)
        {
            try
            {
                var request = new UserQueryRequest
                {
                    Account = account,
                    Realname = realname,
                    Email = email,
                    Phone = phone,
                    Status = status,
                    PageIndex = pageIndex,
                    PageSize = pageSize
                };

                var result = await _userService.GetUserPagedListAsync(request);
                return ResultHelper.Success(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用户分页查询失败");
                return ResultHelper.Error("500", "查询失败");
            }
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        [HttpPost("AddUserAsync")]
        public async Task<ResultApi> AddUserAsync([FromBody] AddUserModelDto user)
        {
            try
            {
                if (string.IsNullOrEmpty(user.Account))
                {
                    return ResultHelper.Error("账号不能为空！");
                }

                if (string.IsNullOrEmpty(user.Realname))
                {
                    return ResultHelper.Error("姓名不能为空！");
                }

                var (success, message) = await _userService.AddUserAsync(user);
                if (success)
                {
                    return ResultHelper.Success(message);
                }
                else
                {
                    return ResultHelper.Error(message);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"添加用户失败 - 账号: {user?.Account}");
                return ResultHelper.Error("500", "添加失败");
            }
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        [HttpPost("UpdateUserAsync")]
        public async Task<ResultApi> UpdateUserAsync([FromForm] UpdateUserModelDto user, IFormFile file)
        {
            try
            {


                if (user.Id <= 0)
                {
                    return ResultHelper.BadRequest("请选择用户！");
                }

                var (success, message) = await _userService.UpdateUserAsync(user, file);
                if (success)
                {
                    return ResultHelper.Success(message);
                }
                else
                {
                    return ResultHelper.Error(message);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"修改用户失败 - 用户ID: {user?.Id}");
                return ResultHelper.Error("500", "修改失败");
            }
        }

        /// <summary>
        /// 启用停用用户
        /// </summary>
        [HttpPost("UpdateUserStatusAsync")]
        public async Task<ResultApi> UpdateUserStatusAsync([FromBody] long userId)
        {
            try
            {
                if (userId <= 0)
                {
                    return ResultHelper.Error("请选择用户！");
                }
                var (success, message) = await _userService.UpdateUserStatusAsync(userId);
                if (success)
                {
                    return ResultHelper.Success(message);
                }
                else
                {
                    return ResultHelper.Error(message);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新用户状态失败 - 用户ID: {userId}");
                return ResultHelper.Error("500", "操作失败");
            }
        }

        /// <summary>
        /// 批量启用停用用户
        /// </summary>
        [HttpPost("UpdateUsersStatusAsync")]
        public async Task<ResultApi> UpdateUsersStatusAsync([FromBody] List<long> ids)
        {
            try
            {
                if (ids == null || ids.Count == 0)
                {
                    return ResultHelper.Error("用户ID列表不能为空！");
                }
                var (success, message) = await _userService.UpdateUsersStatusAsync(ids);
                if (success)
                {
                    return ResultHelper.Success(message);
                }
                else
                {
                    return ResultHelper.Error(message);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"批量更新用户状态失败 - 用户数量: {ids?.Count ?? 0}");
                return ResultHelper.Error("500", "操作失败");
            }
        }

        /// <summary>
        /// 获取用户下拉框
        /// </summary>
        [HttpGet("GetUserDropdownBoxAsync")]
        public async Task<ResultApi> GetUserDropdownBoxAsync()
        {
            try
            {
                var result = await _userService.GetUserDropdownBoxAsync();
                return ResultHelper.Success(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户下拉框失败");
                return ResultHelper.Error("500", "获取失败");
            }
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="updateUserPwdDto"></param>
        /// <returns></returns>
        [HttpPost("UpdateUserPwdAsync")]
        public async Task<ResultApi> UpdateUserPwdAsync([FromBody] UpdateUserPwdDto updateUserPwdDto)
        {
            try
            {
                if (updateUserPwdDto.Id <= 0)
                {
                    return ResultHelper.BadRequest("请选择用户");
                }

                if (string.IsNullOrEmpty(updateUserPwdDto.Password))
                {
                    return ResultHelper.BadRequest("请输入密码");
                }

                if (string.IsNullOrEmpty(updateUserPwdDto.NewPassword))
                {
                    return ResultHelper.BadRequest("请输入密码");
                }

                var (Success, Message) = await _userService.UpdateUserPwdAsync(updateUserPwdDto.Id, updateUserPwdDto.Password, updateUserPwdDto.NewPassword);
                if (Success)
                {
                    return ResultHelper.Success(Message);
                }
                else
                {
                    return ResultHelper.Error(Message);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改用户密码失败");
                return ResultHelper.Error("500", "获取失败");
            }
          
        }
    }
}